// request拦截器
import axios from 'axios'
import { alertMsg, alertMsgOnce } from '@/components/alertMsg/index'
import { clearLocalStorage, routerPush, setLog, getStorageKey } from '@/utils/common'
let loginFail = false
// 创建axios实例
const service = axios.create({
  timeout: null // 请求超时时间
})
let serviceTips = '服务器超时'
// request拦截器
service.interceptors.request.use(
  config => {
    let userData = localStorage.getItem('userData') || {}
    if (userData) {
      try {
        userData = JSON.parse(userData) || {}
      } catch (ex) {
        userData = {}
      }
    }
    const corpId = userData.corpId
    // 设置请求头
    let headers = 'application/json;charset=UTF-8'
    // 是否携带token
    let tokenFlag = true
    // 是否修改请求信息
    if (config.opts) {
      // 获取携带token状态
      tokenFlag = config.opts ? config.opts.token : true
      // 获取请求头
      headers = config.opts.Header ? config.opts.Header : 'application/json;charset=UTF-8'
      // 拓展头部参数
      const Head = config.opts.Head
      if (Head) {
        for (const key in Head) {
          config.headers[key] = Head[key]
        }
      }
    }

    if (corpId) {
      config.headers.corpAB = corpId
    }
    // 设置请求格式
    config.headers['Content-Type'] = headers
    if (config.method === 'get') {
      config.params = {
        _t: new Date().getTime(),
        ...config.params
      }
    }
    return config
  },
  (err) => {
    return Promise.reject(err)
  }
)

// http response 服务器响应拦截器
service.interceptors.response.use(
  async (response)=>{
     const codeString =
      response.data && response.data.code ? response.data.code.toString() : ''
    const _consoleRedirectUrl = getStorageKey('consoleRedirectUrl')
    if (`${codeString[2]}${codeString[3]}` === '10') {
      globalAlterWithoutVm({
        type: response.data.code.toString(),
        msg: response.data.msg
      })
      return response
    }else{
      
      switch (response.data.code) {
        case -401:
          if (!loginFail) {
            loginFail = true
            if (!(response.config && response.config.opts && response.config.opts.skipToken)) {
              // 写入重定向地址
              sessionStorage.setItem(_consoleRedirectUrl, encodeURIComponent(window.location.href))
              routerPush({
                mode: 'mpa',
                path: 'login',
                currentRoute: router.currentRoute
              })
            }
            // 10s内只响应一次
            setTimeout(() => {
              loginFail = false
            }, 4000)
          }
          return {
            data: {
              code: '-401',
              msg: null
            }
          }
        case -1:
        case -3:
          // 系统繁忙错误
          // alertMsgOnce(response.data.msg, 'warning', 4000)
          return response
        default:
          return response
      }
    }   
  },
  (error) => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          error.response.data = '登录超时，重新登录'
          localStorage.setItem(_redirectUrlKey, encodeURIComponent(window.location.href))
          router.replace({
            name: 'login'
          })
          break
        case 404:
          error.response.data = '资源不存在'
          break
        case 406:
          error.response.data = '头部无携带token'
          break
        case 412:
          // 拦截错误
          error.response.data = '秘钥失效'
          break
        case 415:
          error.response.data = '请求type有误'
          break
        case 500:
          error.response.data = '服务器异常'
          break
      }
      serviceTips = error.response.data
    }
    // 此处可自定义提示方式
    console.log(serviceTips)
    return Promise.reject(serviceTips)
  }
)
export default service
